package com.ermao.controller;

import com.ermao.pojo.Account;
import com.ermao.service.AccountService;
import com.ermao.utils.CheckValidUtils;
import com.ermao.utils.Result;
import com.ermao.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author Ermao
 * Date: 2021/8/31 1:03
 */
@RestController
@RequestMapping("/api/v1/users/accounts")
public class AccountController {


	private AccountService accountService;

	@Autowired
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	@PostMapping("")
	public Result addAccount(@RequestParam("userId") Integer userId,
							 @RequestParam("accountAmount") Double accountAmount,
							 @RequestParam("accountType") Integer accountType,
							 @RequestParam("categoryId") Integer categoryId,
							 @RequestParam("accountTime") Date accountTime,
							 @RequestParam("accountComment") String accountComment) {

		if (!CheckValidUtils.CheckAccountValid(accountAmount, accountType, accountTime, accountComment)) {
			return ResultGenerator.genFailResult("添加记录失败，检查记录格式");
		}
		if (accountService.addAnAccount(userId, accountAmount, accountType, categoryId, accountTime, accountComment)) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult("添加记录失败");
		}

	}

	@DeleteMapping("/{accountId}")
	public Result deleteAccount(@PathVariable("accountId") Integer accountId) {
		if (accountService.deleteAnAccount(accountId)) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult("删除失败");
		}
	}

	@PutMapping("")
	public Result modifyAccount(@RequestParam("accountId") Integer accountId,
								@RequestParam("accountAmount") Double accountAmount,
								@RequestParam("accountType") Integer accountType,
								@RequestParam("categoryId") Integer categoryId,
								@RequestParam("accountTime") Date accountTime,
								@RequestParam("accountComment") String accountComment) {
		if (!CheckValidUtils.CheckAccountValid(accountAmount, accountType, accountTime, accountComment)) {
			return ResultGenerator.genFailResult("记录参数不合法");
		}
		if (accountService.updateAnAccount(accountId, accountAmount, accountType, categoryId, accountTime, accountComment)) {
			return ResultGenerator.genSuccessResult();
		} else {
			return ResultGenerator.genFailResult("修改失败");
		}
	}

	@GetMapping("/{accountId}")
	public Result getAccount(@PathVariable("accountId") Integer accountId) {
		Account account = accountService.selectAnAccountByAccountId(accountId);
		if (account != null) {
			return ResultGenerator.genSuccessResult(account);
		} else {
			return ResultGenerator.genFailResult("查询详情错误");
		}
	}
}
